﻿using System;
using Facebook.Rest;
#if WINDOWSPHONE
using Facebook.Utility;
using Facebook.Schema;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Controls.Primitives;
using System.Text.RegularExpressions;
using System.Collections;
using System.Windows.Navigation;

namespace Facebook.Session
{
    /// <summary>
    /// Represents session object for desktop apps
    /// </summary>
    public class WindowsPhoneSession : FacebookSession
    {
        //const string _loginUrl = "http://m.facebook.com/login.php?api_key={0}&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true";
        //const string _loginUrl = @"http://www.facebook.com/login.php?api_key={0}&nochrome=true&connect_display=wap&display=wap&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access";
        const string _loginUrl = @"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri=http://facebook.claritycon.com/connect/login_success.html&type=user_agent&display=popup&scope={1}";
        
        private System.Windows.Controls.Primitives.Popup _popup = new Popup();
        private WebBrowser _webBrowser = new WebBrowser();

        #region Public Methods
        public bool PermissionMode { get; set; }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="appKey">Application Key</param>
        /// <param name="isWPF">true for WPF, false for winform</param>
        public WindowsPhoneSession(string appKey, string appSecret)
            : this(appKey, appSecret, null, null)
        { }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="appKey">Application Key</param>
        /// <param name="isWPF">true for WPF, false for winform</param>
        /// <param name="permissions">list of extended permissions to prompt for upon login</param>
        public WindowsPhoneSession(string appKey, string appSecret, List<Enums.ExtendedPermissions> permissions)
            : this(appKey, appSecret, null, null, permissions)
        { }

        /// <summary>
        /// Constructor - You should not need login function when using this constructor as this is a previously cached session
        /// </summary>
        /// <param name="appKey">Application Key</param>
        /// <param name="sessionSecret">Session secret - If previously cached</param>
        /// <param name="sessionKey">Session key - If previously cached</param>
        public WindowsPhoneSession(string appKey, string appSecret, string sessionSecret, string sessionKey)
            : this(appKey, appSecret, sessionSecret, sessionKey, null)
        { }
        /// <summary>
        /// Constructor - You should not need login function when using this constructor as this is a previously cached session
        /// </summary>
        /// <param name="appKey">Application Key</param>
        /// <param name="sessionSecret">Session secret - If previously cached</param>
        /// <param name="sessionKey">Session key - If previously cached</param>
        /// <param name="isWPF">true for WPF, false for winform</param>
        /// <param name="permissions">list of extended permissions to prompt for upon login</param>
        public WindowsPhoneSession(string appKey, string appSecret, string sessionSecret, string sessionKey, List<Enums.ExtendedPermissions> permissions)
        {
            this.ApplicationKey = appKey;
            this.SessionSecret = sessionSecret;
            this.SessionKey = sessionKey;
            this.ApplicationSecret = appSecret;
            RequiredPermissions = permissions;

        }
        /// <summary>
        /// Logs into session
        /// </summary>
        public override void Login()
        {
            _webBrowser.Navigated += new EventHandler<NavigatedEventArgs>(webBrowser_Navigated);
            _webBrowser.ScriptNotify += new EventHandler<NotifyEventArgs>(_webBrowser_ScriptNotify);

            Border border = new Border();
            border.Background = new SolidColorBrush(Colors.White);
            border.BorderThickness = new Thickness(10);
            border.BorderBrush = new SolidColorBrush(Colors.Gray);
            border.CornerRadius = new CornerRadius(5);

            _webBrowser.Width = 390;
            _webBrowser.Height = 720;

            _popup.Opened += delegate
            {
                PopupOpened();
            };

            border.Child = _webBrowser;
            _popup.Child = border;
            _popup.VerticalOffset = 30;
            _popup.HorizontalOffset = 35;
            _popup.IsOpen = true;
        }

        void _webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            throw new NotImplementedException();
        }

        public void PopupOpened()
        {
                this._webBrowser.Navigate(new Uri(GetLoginUrl()));
        }


        private void webBrowser_Navigated(object sender, NavigatedEventArgs e)
        {
            //if (e.Uri.AbsolutePath.StartsWith("/connect/login_success.html"))
            //{
            //    if (string.IsNullOrEmpty(SessionKey))
            //    {
            //        var api = new Api(this);
            //        api.Auth.GetSessionAsync(ParseQueryString(HttpUtility.UrlDecode(e.Uri.Query).Substring(1))["auth_token"], GetSessionCompleted, null);
            //    }

            //}
        }
        private void GetSessionCompleted(session_info sessionInfo, Object state, FacebookException e)
        {
            ExtractSessionInfo(sessionInfo);
            CompleteLogin();
        }

        private Dictionary<string, string> ParseQueryString(string qstring)
        {
            //simplify our task
            qstring = qstring + "&";

            Dictionary<string, string> outc = new Dictionary<string, string>();

            Regex r = new Regex(@"(?<name>[^=&]+)=(?<value>[^&]+)&", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            IEnumerator _enum = r.Matches(qstring).GetEnumerator();
            while (_enum.MoveNext() && _enum.Current != null)
            {
                outc.Add(((Match)_enum.Current).Result("${name}"),
                        ((Match)_enum.Current).Result("${value}"));
            }

            return outc;
        }
        private void CompleteLogin()
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                _popup.IsOpen = false;
            }));
            OnLoggedIn(null);
        }

        private void ExtractSessionInfo(session_info sessionInfo)
        {
            this.SessionExpires = sessionInfo.expires > 0 ? true : false;
            if (SessionExpires)
            {
                this.ExpiryTime = DateHelper.ConvertUnixTimeToDateTime(sessionInfo.expires);
            }
            this.SessionKey = sessionInfo.session_key;
            this.SessionSecret = sessionInfo.secret;

            if (sessionInfo.uid > 0)
            {
                this.UserId = sessionInfo.uid;
            }

        }

        /// <summary>
        /// logs out of session
        /// </summary>
        public override void Logout()
        {
            OnLoggedOut(null);
        }


        /// <summary>
        /// Gets login url which can be used to login to facebook server
        /// </summary>
        /// <returns>This method returns the Facebook Login URL.</returns>
        public string GetLoginUrl()
        {
            string loginUrl = String.Format(_loginUrl, ApplicationKey, PermissionsToString(RequiredPermissions));

            return loginUrl;
        }

        #endregion

    }
}
#endif


